package org.cjlm.ui.db; 
 
import com.fasterxml.jackson.core.type.TypeReference; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import java.io.File; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.*; 
import java.util.concurrent.ConcurrentHashMap; 
 
public class DataSourceManager {
    private static final String CONFIG_DIR = System.getProperty("user.home")  + "/.toolbox";
    private static final String CONFIG_FILE = CONFIG_DIR + "/datasources.json"; 
    private static final Map<String, DataSourceConfig> cache = new ConcurrentHashMap<>();
    private static String defaultDataSourceId;
 
    static {
        loadFromFile();
    }
 
    private static void loadFromFile() {
        try {
            Path path = Paths.get(CONFIG_FILE); 
            if (Files.exists(path))  {
                ObjectMapper mapper = new ObjectMapper();
                List<DataSourceConfig> configs = mapper.readValue(path.toFile(),  
                        new TypeReference<List<DataSourceConfig>>() {});
                
                configs.forEach(config  -> {
                    cache.put(config.getId(),  config);
                    if (config.isDefault())  defaultDataSourceId = config.getId(); 
                });
            }
        } catch (Exception e) {
            System.err.println(" 数据源加载失败: " + e.getMessage()); 
        }
    }
 
    private static void saveToFile() {
        try {
            File dir = new File(CONFIG_DIR);
            if (!dir.exists())  dir.mkdirs(); 
            
            ObjectMapper mapper = new ObjectMapper();
            mapper.writerWithDefaultPrettyPrinter() 
                  .writeValue(new File(CONFIG_FILE), new ArrayList<>(cache.values())); 
        } catch (Exception e) {
            System.err.println(" 数据源保存失败: " + e.getMessage()); 
        }
    }
 
    public static void addDataSource(DataSourceConfig config) {
        if (config.getId()  == null) config.setId(UUID.randomUUID().toString()); 
        config.setLastModified(System.currentTimeMillis()); 
        cache.put(config.getId(),  config);
        saveToFile();
    }
 
    public static void updateDataSource(DataSourceConfig config) {
        config.setLastModified(System.currentTimeMillis()); 
        cache.put(config.getId(),  config);
        saveToFile();
    }
 
    public static void deleteDataSource(String id) {
        if (id.equals(defaultDataSourceId))  defaultDataSourceId = null;
        cache.remove(id); 
        saveToFile();
    }
 
    public static void setDefaultDataSource(String id) {
        cache.values().forEach(c  -> c.setDefault(c.getId().equals(id))); 
        defaultDataSourceId = id;
        saveToFile();
    }

//    public static DataSourceConfig getDefaultDataSource() {
//        return cache.values().stream().filter(DataSourceConfig::isDefault).findFirst().orElse(null);
//    }
 
    public static DataSourceConfig getDataSource(String id) {
        return cache.get(id); 
    }
 
    public static List<DataSourceConfig> getAllDataSources() {
        return new ArrayList<>(cache.values()); 
    }
 
    public static DataSourceConfig getDefaultDataSource() {
        return defaultDataSourceId != null ? cache.get(defaultDataSourceId)  : null;
    }
}